﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Thrift.Utility
{
    public abstract class ThriftService
    {
        protected virtual string Excute<Q>(StandRequest<Q> request, Func<StandRequest<Q>, string> func)
        {
            Statistic(request);
            if (request.IsValid())
            {
                try
                {
                    string result = string.Empty;
                    if (func != null)
                    {
                        result = func(request);
                    }
                    StandResponse<string> response = new StandResponse<string>
                    {
                        Code = "0",
                        Desc = "SUCCESS",
                        Data = result
                    };
                    return SerializeHelper.JsonSerialize2(response);
                }
                catch (Exception ex)
                {
                    CatchException(ex);
                    StandResponse<string> response = new StandResponse<string>
                    {
                        Code = "-2",
                        Desc = "服务端异常",
                        Data = string.Empty
                    };
                    return SerializeHelper.JsonSerialize2(response);
                }
            }
            StandResponse<string> res = new StandResponse<string>
            {
                Code = "-1",
                Desc = "请求数据异常",
                Data = string.Empty
            };
            return SerializeHelper.JsonSerialize2(res);
        }

        /// <summary>
        /// 统计，每个接口的访问次数、客户端到服务端的传输时间等
        /// </summary>
        /// <typeparam name="Q"></typeparam>
        /// <param name="request"></param>
        protected abstract void Statistic<Q>(StandRequest<Q> request);

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="ex"></param>
        protected abstract void CatchException(Exception ex);
    }
}
